﻿using System; 
using System.Collections.Generic;
using System.Text;
using XXX.Models;
using fuzhu;
using System.Data; 
using XXX.Models.XXXEntities;
using LH.U8API.Bus;
using ADODB;
using XXX.Common;
using System.Data.SqlClient;
using GLY_XieTong;
using System.ServiceModel;
using ServiceReference1;
using System.Xml.Linq;
using System.Linq;
using U8COWeb;
using LH.Model.PU;
using LH.Model.ST;
using SqlSugar;
using static GLY_XieTong.TongBu;
using Microsoft.EntityFrameworkCore.Metadata;
using System.ComponentModel.DataAnnotations;

namespace XXX.Bo
{
    public static class WMSService
    {

        
       // 获取PDA上的版本号
        public static RetModelbool GetPdaVersion()
        {

            string sql = string.Format("select cvalue from ZDY_WMS_PARA WHERE CCODE='PdaVersion' ");
            string cVersion = DbHelper.GetDbString(DbHelper2.ExecuteScalar(sql, CanShu.conStr));
            return DBService.ReOKbool(cVersion);
        }



        // 更新pda版本好
        public static RetModelbool UpdatePdaVersion(string cNewVersion)
        {

            string sql = $"update ZDY_WMS_PARA set cvalue='{cNewVersion}' WHERE CCODE='PdaVersion' ";
            string cVersion = DbHelper.GetDbString(DbHelper2.ExecuteNonQuery(sql, CanShu.conStr));
            if (cVersion=="1")
            {
                return DBService.ReOKbool("更新完成");
            }
            else
            {
                return DBService.ReOKbool("更新失败");
            } 
        }


        /// <summary>
        /// 根据采购订单生成到货单
        /// </summary>
        /// <param name="iid"></param>
        /// <returns></returns>
        public static RetModelbool Pu_Arrival(YiJingPu_ArrivalVouch model)
        {
            try
            {
                string conStr = DBService.GetConStr(model.cAccount);
                if (string.IsNullOrEmpty(conStr))
                {
                    throw new Exception("未配置账套数据库");
                }

                if (model.ItemList.Count == 0)
                {
                    return DBService.ReErrorbool("没有明细数据，无法保存");
                }
                RetModel retModel = new RetModel();
                //检查QID

                string sql = string.Format("select count(*) sl from Pu_ArrivalVouch where cdefine14='{0}'", model.QID);
                int icnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sql, conStr));
                if (icnt > 0)
                {
                    return DBService.ReErrorbool("该任务已执行");
                }

                //根据单据号区分

              
                //插入U8
                try
                {

                    PuArrivalVouch.Head rdHead = new PuArrivalVouch.Head();
 
                    rdHead.cbustype = model.cBusType;
                    rdHead.ddate =DbHelper.GetDbDate(model.dDate).ToString("yyyy-MM-dd");
                    rdHead.ccode = model.cCode;
                    rdHead.cvencode = model.cVenCode;
                    //rdHead.cdepcode = model.cDepCode;
                    //rdHead.cpersoncode = model.cPersonCode;
                    rdHead.cpocode = model.cPOID;
                    rdHead.cmemo = model.cMemo;
                    rdHead.cmaker = model.cMaker;
                    rdHead.cdefine1 = model.cCode;   //避免系统编码，没有了传入的到货单的编码
                    rdHead.cdefine14 = model.QID;
                    rdHead.bnegative = "0";  //必须有，不然报类型不匹配
                    rdHead.ibilltype = "0"; //必须有，不然报类型不匹配
                    rdHead.idiscounttaxtype = "0"; //必须有，不然报类型不匹配
                    rdHead.editprop = "A";
                    rdHead.id = "0";


                    List<LH.Model.PU.PuArrivalVouch.Body> bodies = new List<LH.Model.PU.PuArrivalVouch.Body>();

                    for (int i = 0; i < model.ItemList.Count; i++)
                    {
                        LH.Model.PU.PuArrivalVouch.Body body = new LH.Model.PU.PuArrivalVouch.Body();
                        body.cinvcode = model.ItemList[i].cInvCode;

                        body.cfree1 = model.ItemList[i].cFree1;
                        //body.cfree1 = DataChuli.getBanben(model.ItemList[i].cFree1);
                        body.iposid = model.ItemList[i].iPOsID;
                        body.cwhcode = model.ItemList[i].cWhCode;
                        //body.bgsp = model.materialList[i].checkid;
                        //body.dpdate = model.ItemList[i].manufactureDate;
                        body.iquantity = model.ItemList[i].iQuantity;
                        body.cbatch = model.ItemList[i].cBatch;
                        if (string.IsNullOrEmpty(model.ItemList[i].dMadeDate))
                        {
                            body.dpdate = model.ItemList[i].dMadeDate;
                        }
                       
                        //body.inum ="0";
                        body.editprop = "A";
                        body.irowno = model.ItemList[i].iRowNo;
                        bodies.Add(body);
                    }


                   
                    LH.Model.PU.PuArrivalVouch entity = new LH.Model.PU.PuArrivalVouch(rdHead, bodies);
                    //根据业务类型区分
                    string cRe = "";
                    
                        cRe = GetInfo.GetPUArrivalInfo(entity, conStr);
                     
                    
                     
                    
                    if (cRe != "ok")
                    {
                        throw new Exception(cRe);
                    }
                    string cerr, cid, ccode;
                    string xmlconfig = XmlOperation.GetConfigXMLFromDBIMS(model.cAccount).ToString();
                    if (!Pu_ArrivalVouchDALCO.AddPu_ArrivalVouch(entity, xmlconfig, out cerr, out cid, out ccode))
                    {
                        throw new Exception(cerr);
                    }
                    if (!Pu_ArrivalVouchDALCO.VerifyPu_ArrivalVouch(cid, "verify", xmlconfig, out cerr))
                    {
                        Pu_ArrivalVouchDALCO.VerifyPu_ArrivalVouch(cid, "delete", xmlconfig, out cerr);
                        throw new Exception(cerr);
                    }
                    ////审核
                    //if (!Rdrecord01DALCO.AddRdrecord01(entity, xmlconfig, out cerr, out cid, out ccode))
                    //{
                    //    throw new Exception(cerr);
                    //}


                    return DBService.ReOKbool();
                }
                catch (Exception ex)
                {
                    return DBService.ReErrorbool(ex.Message);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrorbool(ex.Message);
            }

        }


        
        /// <summary>
        /// 根据委外订单生成到货单
        /// </summary>
        /// <param name="iid"></param>
        /// <returns></returns>
        public static RetModelbool OM_Arrival(YiJingPu_ArrivalVouch model)
        {


            try
            {
                string conStr = DBService.GetConStr(model.cAccount);
                if (string.IsNullOrEmpty(conStr))
                {
                    throw new Exception("未配置账套数据库");
                }

                if (model.ItemList.Count == 0)
                {
                    return DBService.ReErrorbool("没有明细数据，无法保存");
                }
                RetModel retModel = new RetModel();
                //检查QID

                string sql = string.Format("select count(*) sl from Pu_ArrivalVouch where cdefine14='{0}'", model.QID);
                int icnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sql, conStr));
                if (icnt > 0)
                {
                    return DBService.ReErrorbool("该任务已执行");
                }

              

                //插入U8
                try
                {

                    PuArrivalVouch.Head rdHead = new PuArrivalVouch.Head();

                    rdHead.cbustype = "委外加工";
                    rdHead.ddate = DbHelper.GetDbDate(model.dDate).ToString("yyyy-MM-dd");
                    rdHead.ccode = model.cCode;
                    rdHead.cvencode = model.cVenCode;
                    //rdHead.cdepcode = model.cDepCode;
                    //rdHead.cpersoncode = model.cPersonCode;
                    rdHead.cpocode = model.cPOID;
                    rdHead.cmemo = model.cMemo;
                    rdHead.cmaker = model.cMaker;
                    rdHead.cdefine1 = model.cCode;   //避免系统编码，没有了传入的到货单的编码
                    rdHead.cdefine14 = model.QID;
                    rdHead.bnegative = "0";  //必须有，不然报类型不匹配
                    rdHead.ibilltype = "0"; //必须有，不然报类型不匹配
                    rdHead.idiscounttaxtype = "0"; //必须有，不然报类型不匹配
                    rdHead.editprop = "A";
                    rdHead.id = "0";


                    List<LH.Model.PU.PuArrivalVouch.Body> bodies = new List<LH.Model.PU.PuArrivalVouch.Body>();

                    for (int i = 0; i < model.ItemList.Count; i++)
                    {
                        LH.Model.PU.PuArrivalVouch.Body body = new LH.Model.PU.PuArrivalVouch.Body();
                        body.cinvcode = model.ItemList[i].cInvCode;
                        body.cfree1 = model.ItemList[i].cFree1;
                        //body.cfree1 = DataChuli.getBanben(model.ItemList[i].cFree1);
                        //20230405 更改，委外订单和采购订单放一起
                        //co不支持委外到货，先写入到U8，然后后台更新状态
                        body.imainmodetailsid = model.ItemList[i].iPOsID;
                        body.cwhcode = model.ItemList[i].cWhCode;
                        //body.bgsp = model.materialList[i].checkid;
                        //body.dpdate = model.ItemList[i].manufactureDate;
                        body.iquantity = model.ItemList[i].iQuantity;
                        //body.inum = model.ItemList[i].count;
                        body.editprop = "A";
                        body.irowno =(i+1).ToString();
                        bodies.Add(body);
                    }
                  
                  
                    LH.Model.PU.PuArrivalVouch entity = new LH.Model.PU.PuArrivalVouch(rdHead, bodies);
                    string cRe = GetInfo.GetOMArrivalInfo(entity, conStr);
                   

                    if (cRe != "ok")
                    {
                        throw new Exception(cRe);
                    }
                    string cerr, cid, ccode;
                    string xmlconfig = XmlOperation.GetConfigXMLFromDBIMS(model.cAccount).ToString();

                  
                   
                    if (!Pu_ArrivalVouchDALCO.AddPu_ArrivalVouch(entity, xmlconfig, out cerr, out cid, out ccode))
                    {
                        throw new Exception(cerr);
                    }
                    if (!Pu_ArrivalVouchDALCO.VerifyPu_ArrivalVouch(cid,"verify", xmlconfig, out cerr))
                    {
                        throw new Exception(cerr);
                    }
                    //更新iposid，以及委外订单的累计入库数量，入库金额
                    sql = string.Format(@"update a set iposid=imainmodetailsid from PU_ArrivalVouchs a where id={0} ", cid);
                    DbHelper2.ExecuteNonQuery(sql, conStr);

                    sql = string.Format(@"update a set imainmodetailsid=null from PU_ArrivalVouchs a where id={0} ", cid);
                    DbHelper2.ExecuteNonQuery(sql, conStr);
                    sql = string.Format(@"update a set iArrMoney=isnull(iArrMoney,0)+je,iArrQTY=isnull(iarrqty,0)+sl from OM_MODETAILS a
  inner join (select iposid,sum(iquantity)  sl,sum(isum) je from PU_ArrivalVouchs where id={0} group by iPOsID) b on a.MODetailsID=b.iPOsID",
  cid);
                    DbHelper2.ExecuteNonQuery(sql, conStr);

                    ////审核
                    //if (!Rdrecord01DALCO.AddRdrecord01(entity, xmlconfig, out cerr, out cid, out ccode))
                    //{
                    //    throw new Exception(cerr);
                    //}


                    return DBService.ReOKbool();
                }
                catch (Exception ex)
                {
                    return DBService.ReErrorbool(ex.Message);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrorbool(ex.Message);
            }
        }
  
        /// <summary>
        /// 采购发票弃审删除
        /// </summary>
        /// <param name="iid"></param>
        /// <returns></returns>
        public static RetModelbool PU_BillVouch_Delete(YJOAAPVerify model)
        {

            RetModelbool retModel = new RetModelbool();
            try
            {
                if (string.IsNullOrEmpty(model.cAccount) || model.cAccount == "")
                {
                    throw new Exception("必须提供采购单位");
                }
                string conStr = "";
                string sql = string.Format(@"select CSOURCE from zdy_inter_database where dbid='{0}' ", model.cAccount);
                DataTable dt2 = DbHelper2.ExecuteTable(sql, CanShu.conStrInter);
                if (dt2.Rows.Count > 0)
                {
                    conStr = DbHelper.GetDbString(dt2.Rows[0]["CSOURCE"]);
                }
                if (string.IsNullOrEmpty(conStr))
                {
                    throw new Exception("未配置账套数据库");
                }
                if (string.IsNullOrEmpty(model.cCode) || model.cCode == "")
                {
                    throw new Exception("必须提供采购发票单号");

                }

                int iId = 0;

                sql = string.Format(@"SELECT PBVid,cVerifier FROM purbillvouch where cpbvcode='{0}'", model.cCode);
                DataTable dtpo = DbHelper2.ExecuteTable(sql, conStr);
                if (dtpo.Rows.Count == 0)
                {
                    throw new Exception("采购发票单错误，U8中不存在");
                }
                string id =DbHelper.GetDbString(dtpo.Rows[0]["PBVid"]);
                string cVerifier = DbHelper.GetDbString(dtpo.Rows[0]["cVerifier"]);
                string cerr ;
                string xmlconfig = XmlOperation.GetConfigXMLFromDB(model.cAccount).ToString();
                if (!string.IsNullOrEmpty(cVerifier))
                {
                    if (!Pu_BillVouchDALCO.VerifyPurBillVouch(id,  "unverify", xmlconfig, out cerr ))
                    {
                        throw new Exception(cerr);
                    }
                }
                //sql = string.Format(@"update purbillvouch  set iswfcontrolled=0,cVerifier= null  where cpbvcode='{0}' ", model.cCode);
                //DbHelper2.ExecuteNonQuery(sql, conStr);

              
                if (!Pu_BillVouchDALCO.VerifyPurBillVouch(id, "delete", xmlconfig, out cerr))
                {
                    throw new Exception(cerr);
                }

                return DBService.ReOKbool();
            }
            catch (Exception ex)
            {
                return DBService.ReErrorbool(ex.Message);

            }




        }
        /// <summary>
        /// 生成采购发票
        /// </summary>
        /// <param name="iid"></param>
        /// <returns></returns>
        public static RetModelbool Pu_BillVouch(YiJingPu_BillVouch model)
        {
            try
            {
                string conStr = DBService.GetOAConStr(model.cAccount);
                if (string.IsNullOrEmpty(conStr))
                {
                    throw new Exception("未配置账套数据库");
                }

                if (model.ItemList.Count == 0)
                {
                    return DBService.ReErrorbool("没有明细数据，无法保存");
                }
                RetModel retModel = new RetModel();
                //检查QID

                string sql = string.Format("select count(*) sl from Purbillvouch where cdefine14='{0}'", model.QID);
                int icnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sql, conStr));
                if (icnt > 0)
                {
                    return DBService.ReErrorbool("该任务已执行");
                }



                //插入U8
                try
                {

                    PurBillVouch.Head rdHead = new PurBillVouch.Head();
                    rdHead.csource = model.cSource;
                    rdHead.cpbvbilltype = model.cPbvbilltype;
                    rdHead.cbustype = model.cBusType;
                    rdHead.cptcode = model.cPTCode;
                    rdHead.dpbvdate = model.dDate.ToString("yyyy-MM-dd");
                    rdHead.cpbvcode = model.cCode;
                    rdHead.cvencode = model.cVenCode;
                    rdHead.cunitcode = model.cVenCode;//代垫单位
                    rdHead.cdepcode = model.cDepCode;
                    rdHead.cpersoncode = model.cPersonCode;
                    rdHead.cexch_name = model.cExch_name;
                    rdHead.cexchrate = model.cExchrate;
                    rdHead.cpbvmemo = model.cMemo;
                    rdHead.iswfcontrolled = "0";
                    rdHead.cpbvmaker = model.cMaker;
                    rdHead.idiscounttaxtype = "0";
                    rdHead.cpaycode = model.cpaycode;
                    rdHead.ipbvtaxrate = model.ipbvtaxrate;
        //            rdHead.cdefine1 = model.cdefine1;
        //            rdHead.cdefine2 = model.cdefine2;
        //rdHead.cdefine3 = model.cdefine3;
        //            rdHead.cdefine4 = model.cdefine4;
        //            rdHead.cdefine5 = model.cdefine5;
        //            rdHead.cdefine6 = model.cdefine6;
        //            rdHead.cdefine7 = model.cdefine7;
        //            rdHead.cdefine8 = model.cdefine8;
        //            rdHead.cdefine9 = model.cdefine9;
        //            rdHead.cdefine10 = model.cdefine10;
        //            rdHead.cdefine11 = model.cdefine11;
        //            rdHead.cdefine12 = model.cdefine12;
        //            rdHead.cdefine13 = model.cdefine13;
        //            rdHead.cdefine14 = model.cdefine14;
        //            rdHead.cdefine15 = model.cdefine15;
        //            rdHead.cdefine16 = model.cdefine16;
        //            rdHead.cvenpuomprotocol = model.cvenpuomprotocol;
        //            rdHead.dcreditstart = model.dcreditstart;
        //            rdHead.icreditperiod = model.icreditperiod;
        //            rdHead.dgatheringdate = model.dgatheringdate;


                    if (!string.IsNullOrEmpty(DbHelper.GetDbString(model.dVouDate))   && model.dVouDate  != DateTime.MinValue)
                    {

                        rdHead.dvoudate = model.dVouDate.ToString("yyyy-MM-dd"); ;
                    }
                    //rdHead.cverifier = model.cVerifier;
                    //rdHead.cauditdate = model.cAuditDate.ToString("yyyy-MM-dd"); ;
                    rdHead.cdefine1 = model.cCode;   //避免系统编码，没有了传入的到货单的编码
                    rdHead.cdefine14 = model.QID;
                    rdHead.bnegative = "0";
                    rdHead.boriginal = "0";
                    rdHead.bfirst = "0";
                    rdHead.bsettle = "0";
                    rdHead.iflowid = "0";
                    rdHead.iswfcontrolled = "0";
                    rdHead.ireturncount = "0";
                    rdHead.bmerger = "0";
                    rdHead.iverifystateex = "0";
                   
                    //< rs:data xmlns:rs = "urn:schemas-microsoft-com:rowset" > < z:row xmlns:z = "#RowsetSchema"  csource = "采购" cpbvbilltype = "01" cpbvcode = "0000000035" dpbvdate = "2023-01-02T00:00:00" cvencode = "FJIYJSM"   cunitcode = "FJIYJSM"   cdepcode = "SDTW"  cpersoncode = "SH00024"   cexch_name = "人民币" cexch_code = "RMB" cexchrate = "1" ipbvtaxrate = "17"
                    //cincode = "0000000055" cbustype = "普通采购" cpbvmaker = "demo" bnegative = "False" boriginal = "False" bfirst = "False" idiscounttaxtype = "0" cvenregcode = "91350200MA2Y1AR9XL" cvenbank = "中国民生银行厦门分行" cvenaccount = "699766359" cvenperson = "黄鼎钧" cmobilephone = "18559670088" bsettle = "0" iflowid = "0" iprintcount = "0"
                    //cmaketime = "2023-01-02T11:07:54.920000000" iswfcontrolled = "False" iverifystateex = "0" ireturncount = "0" csysbarcode = "||puzl|0000000035" bmerger = "0" editprop = "" /> </ rs:data >
                    List <LH.Model.PU.PurBillVouch.Body> bodies = new List<LH.Model.PU.PurBillVouch.Body>();
                    for (int i = 0; i < model.ItemList.Count; i++)
                    {
                        LH.Model.PU.PurBillVouch.Body body = new LH.Model.PU.PurBillVouch.Body();
                        body.upsotype = model.ItemList[i].upsotype;
                        body.cinvcode = model.ItemList[i].cInvCode;
                        body.cfree1 = model.ItemList[i].cFree1;
                        //body.bgsp = model.materialList[i].checkid;
                        //body.dpdate = model.ItemList[i].manufactureDate;
                        body.ipbvquantity = model.ItemList[i].iQuantity;
                        body.citemcode = model.ItemList[i].cItemCode;
                        body.iposid = DbHelper.GetDbString(model.ItemList[i].iPosid);
                        body.rdsid = DbHelper.GetDbString(model.ItemList[i].iRdsid);
                        if (body.rdsid=="0")
                        {
                            body.rdsid = null;
                        }
                        //body.ccode = DbHelper.GetDbString(model.ItemList[i].iRdsid);
                        body.editprop = "A";
                        body.bservice ="0";
                        body.itaxrate = model.ItemList[i].iTaxrate;
                        body.ivouchrowno = model.ItemList[i].iRowNo;
                        if (string.IsNullOrEmpty(model.ItemList[i].iRowNo))
                        {
                            throw new Exception("表体行号未录入，请录入");
                        }
                        body.ioricost = model.ItemList[i].iOricost;
                        body.ioritaxcost = model.ItemList[i].iOritaxcost;
                        body.iorimoney = model.ItemList[i].iOrimoney;
                        body.ioritaxprice = model.ItemList[i].iOritaxprice;
                        body.iorisum = model.ItemList[i].iOrisum;
                        body.icost = model.ItemList[i].iCost;
                        body.imoney = model.ItemList[i].iMoney;
                        body.itaxprice = model.ItemList[i].iTaxprice;
                        body.isum = model.ItemList[i].iSum;
                        body.cbmemo = model.ItemList[i].cbMemo;
                        body.bgift = "0";
                        body.isPayment = "0";
                        body.isSettle = "0";
                        body.bcosting = "0";
                        body.btaxcost = "0";
                        body.brettax = "0";
                        bodies.Add(body);
                    }
                    //< rs:data xmlns:rs = "urn:schemas-microsoft-com:rowset" > < z:row xmlns:z = "#RowsetSchema"   cinvcode = "0201"
                    //igrouptype = "0" cgroupcode = "01" cbaccounter = "" bservice = "False" iinvexchrate = ".00000000"
                    //binvbatch = "True" ipbvquantity = "2.0000000000" ioricost = "100.0000000000" iorimoney = "200"
                    //ioritaxprice = "26" iorisum = "226" icost = "100.0000000000" imoney = "200" itaxprice = "26" isum = "226" ioritotal = "0"
                    //itotal = "0" bexbill = "False" binvtype = "False" itaxrate = "13.0000000000" rdsid = "1000000475" ioritaxcost = "113.000000"
                    //ccode = "0000000055" upsotype = "rd" isPayment = "0" isSettle = "0" bcosting = "False" btaxcost = "False" brettax = "0"
                    //ivouchrowno = "1"  bgift = "0" editprop = "A" /></ rs:data >
                    LH.Model.PU.PurBillVouch entity = new LH.Model.PU.PurBillVouch(rdHead, bodies);
                    string cRe = GetInfo.GetPUBillInfo(entity, conStr);


                    if (cRe != "ok")
                    {
                        throw new Exception(cRe);
                    }
                    string cerr, cid, ccode;
                    string xmlconfig = XmlOperation.GetConfigXMLFromDB(model.cAccount).ToString();
                    if (!Pu_BillVouchDALCO.AddPurBillVouch(entity, xmlconfig, out cerr, out cid, out ccode))
                    {
                        throw new Exception(cerr);
                    }
                    if (!Pu_BillVouchDALCO.VerifyPurBillVouch(cid,"verify", xmlconfig, out cerr ))
                    {
                        throw new Exception(cerr);
                    }
//                    sql = string.Format(@"update purbillvouch set cVerifier='{0}',cAuditDate='{1}',cAuditTime= GETDATE(),IsWfControlled=0
//where  cpbvcode='{2}'", model.cVerifier, model.dDate, model.cCode);
//                    DbHelper2.ExecuteNonQuery(sql, conStr);
                    ////审核
                    //if (!Rdrecord01DALCO.AddRdrecord01(entity, xmlconfig, out cerr, out cid, out ccode))
                    //{
                    //    throw new Exception(cerr);
                    //}


                    return DBService.ReOKbool();
                }
                catch (Exception ex)
                {
                    return DBService.ReErrorbool(ex.Message);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrorbool(ex.Message);
            }

        }


        /// <summary>
        /// 修改采购发票
        /// </summary>
        /// <param name="iid"></param>
        /// <returns></returns>
        public static RetModelbool Pu_BillVouch_Modify(YiJingPu_BillVouch model)
        {
            try
            {
                string conStr = DBService.GetOAConStr(model.cAccount);
                if (string.IsNullOrEmpty(conStr))
                {
                    throw new Exception("未配置账套数据库");
                }

                if (model.ItemList.Count == 0)
                {
                    return DBService.ReErrorbool("没有明细数据，无法保存");
                }
                RetModel retModel = new RetModel();

               string sql = string.Format(@"SELECT PBVid,cVerifier FROM purbillvouch where cpbvcode='{0}'", model.cCode);
                DataTable dtpo = DbHelper2.ExecuteTable(sql, conStr);
                if (dtpo.Rows.Count == 0)
                {
                    throw new Exception("采购发票单错误，U8中不存在");
                }
                string id = DbHelper.GetDbString(dtpo.Rows[0]["PBVid"]);
                string cVerifier = DbHelper.GetDbString(dtpo.Rows[0]["cVerifier"]);

                sql = string.Format(@"SELECT count(*) sl FROM purbillvouchs where pbvid='{0}' and dSDate is not null", id);
                int icnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sql, conStr));
                if (icnt > 0)
                {
                    throw new Exception("采购发票已结算，不可修改");
                }



                string cerr, cid, ccode;
                string xmlconfig = XmlOperation.GetConfigXMLFromDB(model.cAccount).ToString();
                //先弃审
                if (!string.IsNullOrEmpty(cVerifier))
                {
                    if (!Pu_BillVouchDALCO.VerifyPurBillVouch(id, "unverify", xmlconfig, out cerr))
                    {
                        throw new Exception(cerr);
                    }
                }
                

                //插入U8
                try
                {

                    PurBillVouch.Head rdHead = new PurBillVouch.Head();
                    rdHead.pbvid = id;
                    rdHead.csource = model.cSource;
                    rdHead.cpbvbilltype = model.cPbvbilltype;
                    rdHead.cbustype = model.cBusType;
                    rdHead.cptcode = model.cPTCode;
                    rdHead.dpbvdate = model.dDate.ToString("yyyy-MM-dd");
                    rdHead.cpbvcode = model.cCode;
                    rdHead.cvencode = model.cVenCode;
                    rdHead.cunitcode = model.cVenCode;//代垫单位
                    rdHead.cdepcode = model.cDepCode;
                    rdHead.cpersoncode = model.cPersonCode;
                    rdHead.cexch_name = model.cExch_name;
                    rdHead.cexchrate = model.cExchrate;
                    rdHead.cpbvmemo = model.cMemo;
                    rdHead.iswfcontrolled = "0";
                    rdHead.cpbvmaker = model.cMaker;
                    rdHead.idiscounttaxtype = "0";
                    rdHead.cpaycode = model.cpaycode;
                    rdHead.ipbvtaxrate = model.ipbvtaxrate;
                    //            rdHead.cdefine1 = model.cdefine1;
                    //            rdHead.cdefine2 = model.cdefine2;
                    //rdHead.cdefine3 = model.cdefine3;
                    //            rdHead.cdefine4 = model.cdefine4;
                    //            rdHead.cdefine5 = model.cdefine5;
                    //            rdHead.cdefine6 = model.cdefine6;
                    //            rdHead.cdefine7 = model.cdefine7;
                    //            rdHead.cdefine8 = model.cdefine8;
                    //            rdHead.cdefine9 = model.cdefine9;
                    //            rdHead.cdefine10 = model.cdefine10;
                    //            rdHead.cdefine11 = model.cdefine11;
                    //            rdHead.cdefine12 = model.cdefine12;
                    //            rdHead.cdefine13 = model.cdefine13;
                    //            rdHead.cdefine14 = model.cdefine14;
                    //            rdHead.cdefine15 = model.cdefine15;
                    //            rdHead.cdefine16 = model.cdefine16;
                    //            rdHead.cvenpuomprotocol = model.cvenpuomprotocol;
                    //            rdHead.dcreditstart = model.dcreditstart;
                    //            rdHead.icreditperiod = model.icreditperiod;
                    //            rdHead.dgatheringdate = model.dgatheringdate;


                    if (!string.IsNullOrEmpty(DbHelper.GetDbString(model.dVouDate)) && model.dVouDate != DateTime.MinValue)
                    {

                        rdHead.dvoudate = model.dVouDate.ToString("yyyy-MM-dd"); ;
                    }
                    //rdHead.cverifier = model.cVerifier;
                    //rdHead.cauditdate = model.cAuditDate.ToString("yyyy-MM-dd"); ;
                    rdHead.cdefine1 = model.cCode;   //避免系统编码，没有了传入的到货单的编码
                    rdHead.cdefine14 = model.QID;
                    rdHead.bnegative = "0";
                    rdHead.boriginal = "0";
                    rdHead.bfirst = "0";
                    rdHead.bsettle = "0";
                    rdHead.iflowid = "0";
                    rdHead.iswfcontrolled = "0";
                    rdHead.ireturncount = "0";
                    rdHead.bmerger = "0";
                    rdHead.iverifystateex = "0";

                    //< rs:data xmlns:rs = "urn:schemas-microsoft-com:rowset" > < z:row xmlns:z = "#RowsetSchema"  csource = "采购" cpbvbilltype = "01" cpbvcode = "0000000035" dpbvdate = "2023-01-02T00:00:00" cvencode = "FJIYJSM"   cunitcode = "FJIYJSM"   cdepcode = "SDTW"  cpersoncode = "SH00024"   cexch_name = "人民币" cexch_code = "RMB" cexchrate = "1" ipbvtaxrate = "17"
                    //cincode = "0000000055" cbustype = "普通采购" cpbvmaker = "demo" bnegative = "False" boriginal = "False" bfirst = "False" idiscounttaxtype = "0" cvenregcode = "91350200MA2Y1AR9XL" cvenbank = "中国民生银行厦门分行" cvenaccount = "699766359" cvenperson = "黄鼎钧" cmobilephone = "18559670088" bsettle = "0" iflowid = "0" iprintcount = "0"
                    //cmaketime = "2023-01-02T11:07:54.920000000" iswfcontrolled = "False" iverifystateex = "0" ireturncount = "0" csysbarcode = "||puzl|0000000035" bmerger = "0" editprop = "" /> </ rs:data >
                    List<LH.Model.PU.PurBillVouch.Body> bodies = new List<LH.Model.PU.PurBillVouch.Body>();
                    for (int i = 0; i < model.ItemList.Count; i++)
                    {
                        LH.Model.PU.PurBillVouch.Body body = new LH.Model.PU.PurBillVouch.Body();

                        if (string.IsNullOrEmpty(model.ItemList[i].iRowNo))
                        {
                            throw new Exception("表体行号未录入，请录入");
                        }
                        body.ivouchrowno = model.ItemList[i].iRowNo;
                        sql = string.Format("select id from PurBillVouchs where pbvid={0} and ivouchrowno='{1}'", id, body.ivouchrowno);
                        DataTable dtrow = DbHelper2.ExecuteTable(sql, conStr);
                        if (dtrow.Rows.Count > 0)
                        {
                            body.editprop = "M";
                            body.id = DbHelper.GetDbString(dtrow.Rows[0]["id"]);
                            body.pbvid = id;
                        }
                        else
                        {
                            body.editprop = "A";
                        }
                        body.ipbvquantity = model.ItemList[i].iQuantity;
                        if (body.ipbvquantity=="0")
                        {
                            body.editprop = "D";
                        }
                        body.upsotype = model.ItemList[i].upsotype;
                        body.cinvcode = model.ItemList[i].cInvCode;
                        body.cfree1 = model.ItemList[i].cFree1;
                        //body.bgsp = model.materialList[i].checkid;
                        //body.dpdate = model.ItemList[i].manufactureDate;
                        
                        body.citemcode = model.ItemList[i].cItemCode;
                        body.iposid = DbHelper.GetDbString(model.ItemList[i].iPosid);
                        body.rdsid = DbHelper.GetDbString(model.ItemList[i].iRdsid);
                        //body.ccode = DbHelper.GetDbString(model.ItemList[i].iRdsid);
                        if (body.rdsid == "0")
                        {
                            body.rdsid = null;
                        }
                        body.bservice = "0";
                        body.itaxrate = model.ItemList[i].iTaxrate;
                        
                        
                         
                        body.ioricost = model.ItemList[i].iOricost;
                        body.ioritaxcost = model.ItemList[i].iOritaxcost;
                        body.iorimoney = model.ItemList[i].iOrimoney;
                        body.ioritaxprice = model.ItemList[i].iOritaxprice;
                        body.iorisum = model.ItemList[i].iOrisum;
                        body.icost = model.ItemList[i].iCost;
                        body.imoney = model.ItemList[i].iMoney;
                        body.itaxprice = model.ItemList[i].iTaxprice;
                        body.isum = model.ItemList[i].iSum;
                        body.cbmemo = model.ItemList[i].cbMemo;
                        body.bgift = "0";
                        body.isPayment = "0";
                        body.isSettle = "0";
                        body.bcosting = "0";
                        body.btaxcost = "0";
                        body.brettax = "0";
                        bodies.Add(body);
                    }
                    //< rs:data xmlns:rs = "urn:schemas-microsoft-com:rowset" > < z:row xmlns:z = "#RowsetSchema"   cinvcode = "0201"
                    //igrouptype = "0" cgroupcode = "01" cbaccounter = "" bservice = "False" iinvexchrate = ".00000000"
                    //binvbatch = "True" ipbvquantity = "2.0000000000" ioricost = "100.0000000000" iorimoney = "200"
                    //ioritaxprice = "26" iorisum = "226" icost = "100.0000000000" imoney = "200" itaxprice = "26" isum = "226" ioritotal = "0"
                    //itotal = "0" bexbill = "False" binvtype = "False" itaxrate = "13.0000000000" rdsid = "1000000475" ioritaxcost = "113.000000"
                    //ccode = "0000000055" upsotype = "rd" isPayment = "0" isSettle = "0" bcosting = "False" btaxcost = "False" brettax = "0"
                    //ivouchrowno = "1"  bgift = "0" editprop = "A" /></ rs:data >
                    LH.Model.PU.PurBillVouch entity = new LH.Model.PU.PurBillVouch(rdHead, bodies);
                    string cRe = GetInfo.GetPUBillInfo(entity, conStr);


                    if (cRe != "ok")
                    {
                        throw new Exception(cRe);
                    }
                    sql = string.Format(@"SELECT CONVERT(NCHAR, CONVERT(MONEY, ufts),2) as ufts FROM PURBILLVOUCH where pbvid = {0}", id);
                    string ufts =DbHelper.GetDbString(DbHelper2.ExecuteScalar(sql, conStr));
                    entity.head.ufts = ufts;
                    entity.head.editprop = "M";
                    if (!Pu_BillVouchDALCO.ModifyPurBillVouch(entity, xmlconfig, out cerr, out cid, out ccode))
                    {
                        throw new Exception(cerr);
                    }

                    if (!Pu_BillVouchDALCO.VerifyPurBillVouch(id, "verify", xmlconfig, out cerr))
                    {
                        throw new Exception(cerr);
                    }
                    ////审核
                    //if (!Rdrecord01DALCO.AddRdrecord01(entity, xmlconfig, out cerr, out cid, out ccode))
                    //{
                    //    throw new Exception(cerr);
                    //}


                    return DBService.ReOKbool();
                }
                catch (Exception ex)
                {
                    return DBService.ReErrorbool(ex.Message);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrorbool(ex.Message);
            }

        }

       

        

     
      
       
       
          
        
 
        
        /// <summary>
        /// 生成形态转换单
        /// </summary>
        /// <param name="iid"></param>
        /// <returns></returns>
        public static RetModelbool ST_ShapeChange(YiJingShapeChange model)
        {


            try
            {
                string conStr = DBService.GetConStr(model.cAccount);
                if (string.IsNullOrEmpty(conStr))
                {
                    throw new Exception("未配置账套数据库");
                }

                if (model.ItemList.Count == 0)
                {
                    throw new Exception("没有明细数据，无法保存");
                }
                RetModel retModel = new RetModel();
                //检查QID

                string sql = string.Format("select count(*) sl from assemvouch where cdefine14='{0}'", model.QID);
                int icnt = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sql, conStr));
                if (icnt > 0)
                {
                    return DBService.ReOKbool();
                }



                //插入U8
                try
                {
                    LH.Model.ST.AssemVouch.Head rdHead = new LH.Model.ST.AssemVouch.Head();


                    rdHead.dAVDate = DbHelper.GetDbDate(model.dDate).ToString("yyyy-MM-dd");
                    rdHead.cDepCode = model.cDepCode; 
                    rdHead.cAVCode = model.cTVCode;
                    rdHead.cVouchType = "15"; 
                    rdHead.cORdCode = model.cORdCode;
                    rdHead.cIRdCode = model.cIRdCode;

                    //rdHead.cMemo = "testCO";
                    rdHead.cMaker = model.cMaker;
                    //rdHead.cVerifyPerson = model.cHandler;

                    rdHead.cDefine1 = model.cTVCode;
                    rdHead.cDefine14 = model.QID;
                    //rdHead.cdefine1 = model.purchaseReceiptNo;   //入库单号写自定义项1
                    //部门、人员，供应商等，根据表体的订单id取值


                    List<LH.Model.ST.AssemVouch.Body> bodies = new List<LH.Model.ST.AssemVouch.Body>();


                    for (int i = 0; i < model.ItemList.Count; i++)
                    {
                        
                        LH.Model.ST.AssemVouch.Body body = new LH.Model.ST.AssemVouch.Body();
                        body.bAVType = "转换前";
                        body.cWhCode = model.cWhCode; 
                        body.cInvCode = model.ItemList[i].cOInvCode;
                        body.iAVQuantity = model.ItemList[i].iOQuantity;
                        body.cFree1 = model.ItemList[i].cOFree1;
                        //body.cFree1 = DataChuli.getBanben(model.ItemList[i].cOFree1);
                        body.irowno = "1";
                        body.iGroupNO = i.ToString();
                        body.baseqtyd = "1";
                        body.baseqtyn = "1"; 
                        bodies.Add(body);

                        LH.Model.ST.AssemVouch.Body body2 = new LH.Model.ST.AssemVouch.Body();
                        body2.bAVType = "转换后";
                        body2.cWhCode = model.cWhCode;                    
                        body2.cInvCode = model.ItemList[i].cIInvCode;
                        body2.iAVQuantity = model.ItemList[i].iIQuantity;
                        body2.cFree1 = model.ItemList[i].cIFree1;
                        //body2.cFree1 = DataChuli.getBanben(model.ItemList[i].cIFree1);
                        body2.irowno = "2";
                        body2.iGroupNO = i.ToString();
                        body2.baseqtyd = "1";
                        body2.baseqtyn = "1"; 
                        bodies.Add(body2);
                    }
                   

                    LH.Model.ST.AssemVouch entity = new LH.Model.ST.AssemVouch(rdHead, bodies);
                    string cRe = GetInfo.GetShapeChangeInfo(entity, conStr);
                    if (cRe != "ok")
                    {
                        throw new Exception(cRe);
                    }
                    string xmlconfig = XmlOperation.GetConfigXMLFromDBIMS(model.cAccount).ToString();
                    string cerr, cid, ccode;
                    if (!AssemVouchDALCO.AddAssemVouch(entity, xmlconfig, out cerr, out cid, out ccode))
                    {
                        throw new Exception(cerr);
                    }
                    if (!AssemVouchDALCO.VerifyAssemVouch(cid, xmlconfig, "verify", out cerr))
                    {
                        AssemVouchDALCO.VerifyAssemVouch(cid, xmlconfig, "delete", out cerr);
                        throw new Exception(cerr);
                    }
                    
                    sql = string.Format(@"update AssemVouch  set cVerifyPerson='{0}' where id='{1}'",model.cHandler, cid);
                    DbHelper2.ExecuteNonQuery(sql, conStr);


                    //审核其他出入库单
                    sql = string.Format("select cavcode from AssemVouch where id = '{0}'", cid);
                    DataTable dtass = DbHelper2.ExecuteTable(sql, conStr);
                    if (dtass.Rows.Count == 0)
                    {
                        throw new Exception("生单失败");

                    }
                    else
                    {

                        sql = string.Format("select id from rdrecord08 where cbustype='转换入库' and  cbuscode = '{0}'", ccode);
                        string iid8 = DbHelper.GetDbString(DbHelper2.ExecuteScalar(sql, conStr));
                        if (!Rdrecord08DALCO.VerifyRdrecord08(iid8, xmlconfig, "verify", out cerr))
                        {
                            throw new Exception(cerr);
                        }
                        sql = string.Format("select id from rdrecord09 where cbustype='转换出库' and  cbuscode = '{0}'", ccode);
                        string iid9 = DbHelper.GetDbString(DbHelper2.ExecuteScalar(sql, conStr));
                        if (!Rdrecord09DALCO.VerifyRdrecord09(iid9, xmlconfig, "verify", out cerr))
                        {
                            throw new Exception(cerr);
                        };
                    }

                    return DBService.ReOKbool();
                }
                catch (Exception ex)
                {
                    return DBService.ReErrorbool(ex.Message);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrorbool(ex.Message);
            }




        }

        /// <summary>
        /// 插入材料出库单
        /// </summary>
        /// <param name="iid"></param>
        /// <returns></returns>
        public static RetModelbool MO_Close(YiJingMOClose model)
        {

            try
            {
                string conStr = DBService.GetConStr(model.cAccount);
                if (string.IsNullOrEmpty(conStr))
                {
                    throw new Exception("未配置账套数据库");
                }

                
                //插入U8
                try
                {
                    string bWW = model.bWW;
                    if (bWW == "1")
                    {
                        if (model.Is_over == "Y")
                        {
                            string sql = string.Format(@"  update OM_MODetails set dbCloseDate='{1}',dbCloseTime  = getdate(),cbCloser='MES'  where MODetailsID='{0}' ",
                           model.iModid, model.dCloseDate);
                            DbHelper2.ExecuteNonQuery(sql, conStr);
                        }

                    }
                    else
                    {
                        if (model.Is_over == "Y")
                        {
                            string sql = string.Format(@"  update mom_orderdetail set CloseDate='{1}',CloseTime  = getdate(),CloseUser='MES',Status='4'  where MoDId='{0}' ",
                           model.iModid, model.dCloseDate);
                            DbHelper2.ExecuteNonQuery(sql, conStr);
                        }

                    }

                    return DBService.ReOKbool();
                }
                catch (Exception ex)
                {
                    return DBService.ReErrorbool(ex.Message);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrorbool(ex.Message);
            }

        }
        /// <summary>
        /// 获取单据号
        /// </summary>
        /// <param name="cTable">查询的表明，WMS_TASK,WMS_RDRECORD</param>
        /// <returns></returns>
        public static string GetNewcode(string conStr,string cTable)
        {
            string cQianZhui = DateTime.Now.ToString("yyMM");
            int iMax = 0;

            string sql = string.Format(@"select MAX(CCODE) FROM  {1} where ccode like '{0}%'", cQianZhui, cTable);
            iMax = DbHelper.GetDbInt(DbHelper2.ExecuteScalar(sql, conStr));
            string cVouchCode = cQianZhui + "0001";
            if (iMax != 0)
            {
                cVouchCode = (iMax + 1).ToString();
            }
            return cVouchCode;
        }

         

      

    }
}
